package copyengine.utils.tick.node
{
    import copyengine.utils.tick.DoubleLinkNode;

    public class TickObjectNode extends DoubleLinkNode
    {
        public var tickFinishedCallBackFunction:Function;

        public var isNeedRemove:Boolean = false; // an flage to tell mainTick is this node need to be remove

        /**
         *当前的毫秒数
         */
        protected var currentTickTime:int = 0;

        /**
         *每次重复的毫秒数
         */
        private var eachTimeTickTimeCount:int = 0;

        /**
         *剩余重复次数
         */
        protected var remainRepeatTime:int = 0;


        public function TickObjectNode(_callBackFunction:Function, _tickTime:int, _repeatTime:int)
        {
            tickFinishedCallBackFunction = _callBackFunction;
            eachTimeTickTimeCount = _tickTime;
            remainRepeatTime = _repeatTime;
            currentTickTime = 0;
        }

        public final function tick(_elapseTime:int):void
        {
            //先执行TickLogic
            tickLogic(_elapseTime);

            if (currentTickTime >= eachTimeTickTimeCount) {
                //如果当前时间大于检测时间则
                //1 remainTime减少
                //将多出来的时间匀到下次Tick中,这样时间准 比如需要1s返回及1000毫秒后返回
                //正常情况下Tick为每次pass 42ms 但是logic运算或者慢速运行均会降低整个值
                //这样正常情况下Tick 24次返回,慢速情况下也许两三次及返回 但是差值会很大，此时把差值赋给下次Tick
                //这样第二次Tick会尽可能弥补之前差的部分
                currentTickTime -= eachTimeTickTimeCount;
                --remainRepeatTime;
                if (remainRepeatTime <= 0) //repeatTime < 0 会多执行一次
                {
                    isNeedRemove = true;
                }
                if (tickFinishedCallBackFunction != null) {
                    if (tickFinishedCallBackFunction.length == 1) {
                        tickFinishedCallBackFunction(_elapseTime);
                    }
                    else {
                        tickFinishedCallBackFunction();
                    }
                }
            }
        }

        protected function tickLogic(_elapseTime:int):void
        {
            currentTickTime += _elapseTime;
        }

        public function destory():void
        {
            tickFinishedCallBackFunction = null;
        }


    }
}
